from java.io import BufferedReader, InputStreamReader
from java.util.zip import GZIPInputStream
from org.apache.http.client.methods import HttpGet
from org.apache.http.impl.client import HttpClients

class Daily:
	
	host = "https://p33jpcuq7x.re.qweatherapi.com"
	key = "af7df4cbe8d74bc197687961c0fbbc5b"
	
	data = None
	
	def __init__(self, location, day='3d'):
		self.day = day
		self.location = location
		self.httpClient = HttpClients.createDefault()
	
	def request(self):
		
		try:
			request = HttpGet("{}/v7/weather/{}?location={}".format(self.host, self.day, self.location))
			request.setHeader("X-QW-Api-Key", self.key)
			
			response = self.httpClient.execute(request)
			
			entity = response.getEntity()
			input_stream = entity.getContent()
			
			reader = BufferedReader(InputStreamReader(input_stream, "UTF-8"))
			response_body = ""
			line = reader.readLine()
			while line is not None:
				response_body += line
				line = reader.readLine()
				
		finally:
			response.close()
			self.httpClient.close()
		
		self.data = system.util.jsonDecode(response_body)
		
	def save(self):
		self.request()
		
		for row in self.data["daily"]:
			parameters = {
				"fxDate": system.date.parse(row["fxDate"], "yyyy-MM-dd"),
				"sunrise": row["sunrise"],
				"sunset": row["sunset"],
				"tempMax": float(row["tempMax"]),
				"tempMin": float(row["tempMin"]),
				"humidity": float(row["humidity"]),
				"windSpeedDay": float(row["windSpeedDay"]),
				"windSpeedNight": float(row["windSpeedNight"]),
				"precip": float(row["precip"]),
				"CreatedTime": system.date.now()
			}
			
			try:
				system.db.runNamedQuery("weather/insert", parameters = parameters)
			except:
				pass
			
			
			